package com.maxlen.goods.exception;

import com.maxlen.common.exception.ExceptionCode;
import com.maxlen.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.maxlen.goods.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(ExceptionCode.VALID_EXCEPTION).put("data", map);
    }

//    @ExceptionHandler(Throwable.class)
//    public R handleException(Throwable throwable){
//        return R.error(ExceptionCode.UNKNOWN_EXCEPTION).put("data", throwable);
//    }

}
